package com.example.mgs.config;


import com.example.mgs.Handler.NotificationHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.FixedLengthFrameDecoder;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.stream.ChunkedWriteHandler;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class NettyServer {

    @Value("${netty.port:8284}")
    private int PORT;

    private EventLoopGroup bossGroup;
    private EventLoopGroup workerGroup;

    @PostConstruct
    public void start() throws Exception {
        bossGroup = new NioEventLoopGroup();
        workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class) // 使用 NIO 传输通道
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) {
                            ChannelPipeline pipeline = ch.pipeline();
                            // 添加编解码器
                            pipeline.addLast(new HttpServerCodec());
                            pipeline.addLast(new ChunkedWriteHandler());
//                            pipeline.addLast(new CorsHandler());
                            pipeline.addLast(new StringDecoder());
                            pipeline.addLast(new StringEncoder());
                            pipeline.addLast(new FixedLengthFrameDecoder(128));//拆包（128字节）
//                            pipeline.addLast(new HttpObjectAggregator(65536));   //64K，一次性可接收的最大消息内存大小
                            // 设置聚合器大小为 10MB (10 * 1024 * 1024 bytes)
                            pipeline.addLast(new HttpObjectAggregator(10 * 1024 * 1024));//10MB
//                            pipeline.addLast(new WebSocketServerProtocolHandler("/webSocket"));
                            pipeline.addLast(new WebSocketServerProtocolHandler("/ws/notification"));
                            // 添加自定义处理器
                            pipeline.addLast(new NotificationHandler());
                        }
                    })
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .childOption(ChannelOption.SO_KEEPALIVE, true);

            System.out.println("正在启动Netty服务器！！！！！！！" + PORT+"   mgs服务");
            System.out.println("Http端口号：" + PORT);
            // 绑定端口，启动服务器
            ChannelFuture future = bootstrap.bind(PORT).sync();
            log.info("Netty 服务器在端口 {} 上启动", PORT);

            // 等待服务器关闭
            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            log.error("Netty 服务器启动失败" + e.getMessage(), e);
            Thread.currentThread().interrupt();
        }
    }

    @PreDestroy
    public void stop() {
        log.info("netty服务器已停止！");
        workerGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
    }

}